<template>
  <!-- 角色查询 -->
  <el-row>
    <el-col :span="24">
      <el-card class="box-card" id="card">
        <div slot="header" class="clearfix">
          <span>用户管理</span>
          <span
            >-您可以通过搜索或者其他的筛选项对用户的信息进行编辑、删除等管理操作。^_^</span
          >
        </div>
        <el-row>
          <el-col :span="16" :offset="4">
            <el-form ref="form" :model="form" label-width="80px">
              <!-- 用户名称 -->
              <el-form-item label="用户名称">
                <el-input v-model="form.userName"></el-input>
              </el-form-item>
              <!-- 角色 -->
              <el-form-item label="角色">
                <el-select
                  v-model="form.roleId"
                  placeholder="请选择角色"
                  style="width: 100%"
                >
                  <el-option
                    v-for="role in roles"
                    :key="role.roleId"
                    :label="role.roleName"
                    :value="role.roleId"
                  ></el-option>
                </el-select>
              </el-form-item>
              <div class="queryButton">
                <el-button type="primary" @click="search">查询</el-button>
                <el-button @click="resetForm">重置</el-button>
              </div>
            </el-form>
          </el-col>
        </el-row>

        <!-- 表单显示 -->
        <el-row
          type="flex"
          align="bottom"
          v-loading="loading"
          element-loading-text="拼命加载中"
          element-loading-background="rgb(255,255,255)"
        >
          <el-col :span="3">
            <el-button icon="el-icon-circle-plus-outline" @click="addUser"
              >添加用户</el-button
            >
          </el-col>
          <el-col :span="18">
            <el-table
              :data="tableData"
              style="width: 100%"
              border
              height="330px"
              :default-sort="{ prop: 'id', order: 'ascending' }"
            >
              <el-table-column prop="id" label="编号" width="100" sortable>
                <template slot-scope="scope">
                  <!-- <i class="el-icon-s-flag"></i> -->
                  <span style="margin-left: 10px">{{
                    scope.row.doctorId
                  }}</span>
                </template>
              </el-table-column>
              <el-table-column label="用户名" width="250">
                <template slot-scope="scope">
                  <el-popover trigger="hover" placement="top">
                    <p>姓名: {{ scope.row.doctorName }}</p>
                    <p>角色: {{ scope.row.roleName }}</p>
                    <p>所在部门: {{ scope.row.departmentName }}</p>
                    <div slot="reference" class="name-wrapper">
                      <el-tag size="medium">{{ scope.row.doctorName }}</el-tag>
                    </div>
                  </el-popover>
                </template>
              </el-table-column>
              <el-table-column label="角色" width="150">
                <template slot-scope="scope">
                  <span>
                    {{ scope.row.roleName }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column label="部门" width="150">
                <template slot-scope="scope">
                  <span>{{ scope.row.departmentName }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    @click="handleEdit(scope.$index, scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row type="flex" justify="center" class="pagination">
          <el-col>
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="form.currentPage"
              :page-sizes="[5, 10, 20, 40]"
              :page-size="form.pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total"
              background
            >
            </el-pagination>
          </el-col>
        </el-row>
      </el-card>
    </el-col>

    <!-- 修改用户的卡片 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      :close-on-click-modal="false"
    >
      <el-form
        :model="modifyData"
        status-icon
        ref="modifyData"
        label-width="100px"
        class="demo-ruleForm"
        :rules="rules"
      >
        <el-form-item label="姓名" prop="doctorName">
          <el-input
            type="text"
            v-model="modifyData.doctorName"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <template v-if="title == '新增用户信息'">
          <el-form-item label="密码" prop="password">
            <el-input
              type="password"
              v-model="modifyData.password"
              autocomplete="off"
            ></el-input>
          </el-form-item>
        </template>
        <el-form-item label="服务患者数" prop="serviceCount">
          <el-input
            v-model.number="modifyData.serviceCount"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select v-model="modifyData.roleId" placeholder="请选择角色">
            <el-option
              v-for="role in roles"
              :label="role.roleName"
              :value="role.roleId"
              :key="role.roleId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="所属部门" prop="departmentId">
          <el-select v-model="modifyData.departmentId" placeholder="请选择部门">
            <el-option
              :label="department.departmentName"
              :value="department.departmentId"
              v-for="department in departments"
              :key="department.departmentId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="介绍" prop="doctorIntroduce">
          <el-input
            type="textarea"
            v-model="modifyData.doctorIntroduce"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <div>
          <el-button type="primary" @click="submit">提交</el-button>
          <el-button @click="resetModify('modifyData')">清空</el-button>
        </div>
      </el-form>
    </el-dialog>
  </el-row>
</template>

<script>
export default {
  data() {
    var checkServiceCount = (rule, value, callback) => {
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"));
        } else if (value < 0) {
          callback(new Error("服务患者数必须大于0"));
        } else {
          callback();
        }
      }, 100);
    };
    return {
      /**
       * 查询信息
       */

      form: {
        userName: "",
        roleId: "",
        currentPage: 1,
        pageSize: 5
      },
      tableData: [],
      roles: [],
      departments: [],
      total: 5,
      loading: true,
      dialogVisible: false,
      //修改
      modifyData: {
        doctorName: "",
        serviceCount: 0,
        doctorIntroduce: "",
        roleId: "",
        departmentId: "",
        doctorPassword: ""
      },
      rules: {
        doctorName: [
          { required: true, message: "请输入用户名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" }
        ],
        serviceCount: [{ validator: checkServiceCount, trigger: "blur" }],
        roleId: [
          { required: true, message: "请选择用户角色", trigger: "change" }
        ],
        departmentId: [
          {
            required: true,
            message: "请选择用户角色所在的部门",
            trigger: "change"
          }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 6, max: 18, message: "密码的长度为6到18位", trigger: "blur" }
        ]
      },
      title: ""
    };
  },
  methods: {
    /**
     * 搜索按钮点击事件
     */
    search() {
      this.form.currentPage = 1;
      this.onSubmit();
    },
    /**
     * 查询
     */
    onSubmit() {
      // console.log("++++当前的页码：" + this.form.currentPage);
      // console.log("++++每页数：" + this.form.pageSize);
      this.$axios
        .post("/api/biz/user/list", this.form)
        .then(result => {
          let data = result.data;
          if (data.code == 0) {
            this.tableData = data.data.data;
            this.total = data.data.totals;
          } else {
            this.$message.error(data.message);
          }
          this.loading = false;
        })
        .catch(err => {
          this.$message.error(err);
        });
    },
    resetForm() {
      this.form.userName = "";
      this.form.roleId = "";
    },
    /**
     * 编辑用户信息按钮
     */
    handleEdit(index, row) {
      this.title = "修改用户信息";
      let id = row.doctorId;
      this.showDialog(id, row);
    },
    /**
     * 显示对话框
     */
    showDialog(userId, row) {
      //根据id查询用户信息
      if (userId != undefined) {
        this.$axios
          .get("/api/biz/user/get/" + userId)
          .then(result => {
            let data = result.data;
            if (data.code == 0) {
              let user = data.data;
              this.modifyData = user;
              //默认选择当前角色
              if (row != undefined) {
                this.modifyData.roleId = row.roleId;
              }
            } else {
              this.$message.error("获取用户信息失败！");
            }
          })
          .catch(err => {
            this.$message.error(err);
          });
      }

      //获取部门信息
      this.$axios
        .get("/api/biz/department/list")
        .then(result => {
          let data = result.data;
          if (data.code == 0) {
            this.departments = data.data;
            //默认选择当前部门
            if (row != undefined) {
              this.modifyData.departmentId = row.departmentId;
            }
            if (userId == undefined) {
              //将内容清空
              // this.resetModify("modifyData");
            }
            //打开修改窗口
            this.dialogVisible = true;
          } else {
            this.$message.error("获取部门信息失败！");
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    resetModify(formName) {
      this.$refs[formName].resetFields();
    },
    handleDelete(index, row) {
      this.$confirm("是否将用户：【" + row.doctorName + "】 删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$axios
            .get("/api/biz/user/del/" + row.doctorId)
            .then(result => {
              let data = result.data;
              if (data.code == 0) {
                this.$message({
                  type: "success",
                  message: "删除成功！"
                });
                this.onSubmit();
              } else {
                this.$message({
                  type: "error",
                  message: "删除失败！"
                });
              }
            })
            .catch(err => {
              this.$message({
                type: "error",
                message: err
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    /**
     * 分页方法
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.form.pageSize = val;
      this.onSubmit();
    },
    handleCurrentChange(val) {
      console.log(`当前页:` + val);
      this.form.currentPage = val;
      this.onSubmit();
    },
    /**
     * 添加用户
     */
    addUser() {
      this.title = "新增用户信息";
      this.showDialog(undefined, undefined);
    },
    /**
     * 关闭修改窗口
     */
    handleClose(done) {
      this.resetModify("modifyData");
      done();
    },
    /**
     * 提交按钮
     */
    submit() {
      if (this.title == "修改用户信息") {
        this.modifySubmit();
      } else {
        this.addSubmit();
      }
    },
    /**
     * 提交修改
     */
    modifySubmit() {
      this.$axios
        .post("/api/biz/user/modify", this.modifyData)
        .then(result => {
          let data = result.data;
          if (data.code == 0) {
            //关闭修改窗口
            this.dialogVisible = false;
            //将内容清空
            this.resetModify("modifyData");
            //获取列表数据
            this.onSubmit();
            this.$message.success("修改用户成功！");
          } else {
            this.$message.error("修改数据提交失败！");
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    },

    /**
     * 提交新增
     */
    addSubmit() {
      this.title = "新增用户信息";
      this.modifyData.serviceCount = 0;
      this.$axios
        .post("/api/biz/user/addUser", this.modifyData)
        .then(result => {
          let data = result.data;
          if (data.code == 0) {
            //关闭修改窗口
            this.dialogVisible = false;
            //将内容清空
            this.resetModify("modifyData");
            //获取列表数据
            this.onSubmit();

            this.$message.success("新增用户成功！");
          } else {
            this.$message.error("新增数据提交失败！");
          }
        })
        .catch(err => {
          this.$message.error(err);
        });
    }
  },
  //页面初始化时执行
  mounted() {
    //获取角色下拉框数据
    this.$axios
      .get("/api/biz/role/list", {
        headers: { Authorization: sessionStorage.getItem("token") }
      })
      .then(result => {
        if (result.status != 200) {
          this.$message.error("获取角色信息失败！请联系管理员");
          return;
        }
        let data = result.data.data;
        this.roles = data;
      })
      .catch(err => {
        this.$message.error(err);
      });
    //获取列表数据
    this.onSubmit();
  }
};
</script>

<style scoped>
#card {
  width: 100%;
  margin: 0px;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
  border-bottom: 1px solid #ebeef5;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.clearfix {
  text-align: left;
}
.clearfix > span:last-child {
  color: #333333;
  font-size: 13px;
}
.clearfix > span:first-child {
  font-weight: bold;
  color: #59a6f5;
  margin-right: 20px;
}
.queryButton {
  padding-bottom: 20px;
}
.pagination {
  padding-top: 20px;
}

.el-form-item__content {
  margin-left: 100px;
  margin-right: 50px;
}
.el-select {
  width: 100%;
}
.el-dialog__body {
  padding-top: 10px;
}
</style>
